package org.wat.wcy.isi.mmazur.bp.io.model;

import java.io.IOException;
import java.io.RandomAccessFile;
import java.util.Arrays;

import org.apache.commons.lang.StringUtils;
import org.wat.wcy.isi.mmazur.bp.io.BinaryObject;

public class IdDesc extends BinaryObject implements Comparable<IdDesc> {

	public final static String ID_NULL = "00000000-0000-0000-0000-000000000000";
	private static final int ID_SIZE = ID_NULL.length();
	private static final String ID_REGEX = "[a-zA-Z0-9]{8}-[a-zA-Z0-9]{4}-[a-zA-Z0-9]{4}-[a-zA-Z0-9]{12}";
	private String data;
	//8,4,4,12 - sum 
	//example: ff403db1-f47c-4f91-becd-597dfa844144
	
	public IdDesc() {
		data = ID_NULL;
	}
	
	public IdDesc(String id) {
//		if (id == null || id.length() != ID_SIZE) {
//			throw new RuntimeException("NmTokenId contructor");
//		}
		data = id;
	}
	
	public String getData() { 
		return data;
	}
	
	
	public void setData(String data) {
		this.data = data;
	}

	public boolean validate() {
		return new String(data).matches(ID_REGEX);
	}
	
	@Override
	public void write(RandomAccessFile raf) {
		try {
			byte b[] = Arrays.copyOf(data.getBytes(), ID_SIZE);
			raf.write(b);
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

	@Override
	public void read(RandomAccessFile raf) {
		try {
			byte b[] = new byte [ID_SIZE];
			raf.read(b, 0, ID_SIZE);
			data = new String(b).trim();
		} catch (IOException e) {
			e.printStackTrace();
		}
		
	}
	
	
	
	@Override
	public boolean equals(Object obj) {
		if (obj instanceof IdDesc) {
			return StringUtils.equalsIgnoreCase(((IdDesc)obj).data, data);
		}
		return super.equals(obj);
	}

	@Override
	public String toString() {
		return getData();
	}

	public static int sizeOf() {
		return ID_SIZE;
	}

	public boolean isNull() {
		return StringUtils.equalsIgnoreCase(toString(), ID_NULL);
	}

	@Override
	public int compareTo(IdDesc o) {
		if (o == null) {
			return 1;
		}
		if (this.data == null && o.data == null) {
			return 0;
		} else if (this.data == null ^ o.data == null) {
			return this.data == null ? 0 : 1;
		} else {
			return this.data.compareTo(o.data);
		}
	}
}
